<?php
/**
 * Created by PhpStorm.
 * Date: 2021/1/13
 * Time: 4:41 PM
 */
namespace app\admin\model;

use helper\GenerateField;
use think\facade\Db;
use think\Model;

class ModelField extends Model
{
    /**
     * 添加字段
     * @param $param
     * @return array
     */
    public function addField($param)
    {
        try {

            $this->insert($param);
        } catch (\Exception $e) {
            return ['code' => -1, 'data' => [], 'msg' => '系统异常'];
        }

       return ['code' => 0, 'data' => [], 'msg' => 'success'];
    }

    /**
     * 获取模型内容字段列表
     * @param $limit
     * @param $where
     * @return array
     */
    public function getModelFieldList($limit, $where)
    {
        try {

            $list = $this->where($where)->order('id desc')->paginate($limit);
            return ['code' => 0, 'data' => $list, 'msg' => 'ok'];
        } catch (\Exception $e) {

            return ['code' => -1, 'data' => [], 'msg' => $e->getMessage()];
        }
    }

    /**
     * 更新模型字段内容
     * @param $id
     * @param $param
     * @return array
     */
    public function updateModelField($id, $param)
    {
        try {

            $this->where('id', $id)->update($param);
        } catch (\Exception $e) {

            return ['code' => -1, 'data' => [], 'msg' => $e->getMessage()];
        }

        return ['code' => 0, 'data' => [], 'msg' => 'ok'];
    }

    /**
     * 检测并添加内容字段
     * @param $data
     * @param $dtype
     * @return array
     */
    public function checkAndAddField($data, $dtype)
    {
        try {

            $param = [
                'name' => $data['name'],
                'model_id' => $data['model_id'],
                'title' => $data['title'],
                'dtype' => $data['dtype'],
                'define' => $dtype[$data['dtype']]['field'],
                'max_length' => $dtype[$data['dtype']]['len'],
                'dfvalue' => $data['dfvalue'],
                'dfvalue_unit' => $data['dfvalue_unit'],
                'sort_order' => $data['sort_order'],
                'status' => 1,
                'add_time' => date('Y-m-d H:i:s')
            ];

            $has = $this->where('model_id', $param['model_id'])->where('name', $param['name'])
                ->find();
            if (!empty($has)) {
                return ['code' => -2, 'data' => [], 'msg' => '该字段已经存在'];
            }

            $this->insert($param);

            // 找到对应的模型字段表，增加对应的字段
            $modelxModel = new Modelx();
            $modelInfo = $modelxModel->getModelById($param['model_id'])['data'];
            $modelTable = $modelInfo['table'];
            $table = getTablePrefix() . $modelTable . '_content';
            // 得出字段的类型
            $field = GenerateField::parse($param);
            $sql = 'ALTER TABLE `' . $table . '` ADD COLUMN `'
                . $param['name'] . '` ' . $field . ' COMMENT "' . $param['title'] . '";';
            Db::execute($sql);
        } catch (\Exception $e) {

            return ['code' => -1, 'data' => [], 'msg' => $e->getMessage()];
        }

        return ['code' => 0, 'data' => [], 'msg' => '添加成功'];
    }

    /**
     * 获取字段信息
     * @param $fieldId
     * @return array
     */
    public function getFieldInfoById($fieldId)
    {
        try {

            $info = $this->where('id', $fieldId)->find();
        } catch (\Exception $e) {
            return ['code' => -1, 'data' => [], 'msg' => $e->getMessage()];
        }

        return ['code' => 0, 'data' => $info, 'msg' => 'success'];
    }

    /**
     * 检测并编辑内容字段
     * @param $data
     * @param $dtype
     * @return array
     */
    public function checkAndEditField($data, $dtype)
    {
        try {

            $param = [
                'name' => $data['name'],
                'model_id' => $data['model_id'],
                'title' => $data['title'],
                'dtype' => $data['dtype'],
                'define' => $dtype[$data['dtype']]['field'],
                'max_length' => $dtype[$data['dtype']]['len'],
                'dfvalue' => $data['dfvalue'],
                'dfvalue_unit' => $data['dfvalue_unit'],
                'sort_order' => $data['sort_order'],
                'update_time' => date('Y-m-d H:i:s')
            ];

            $has = $this->where('id', '<>', $data['id'])->where('model_id', $data['model_id'])
                ->where('name', $data['name'])
                ->find();
            if (!empty($has)) {
                return ['code' => -2, 'data' => [], 'msg' => '该字段已经存在'];
            }

            $this->where('id', $data['id'])->update($param);

            // 找到对应的模型字段表，编辑对应的字段
            $modelxModel = new Modelx();
            $modelInfo = $modelxModel->getModelById($param['model_id'])['data'];
            $modelTable = $modelInfo['table'];
            $table = getTablePrefix() . $modelTable . '_content';

            // 字段名字更改的话，则删除旧字段，增加新字段
            if ($data['old_name'] != $data['name']) {

                $sql = 'ALTER TABLE `' . $table . '` DROP COLUMN `' . $param['name'] . '`;';
                Db::execute($sql);

                // 得出字段的类型
                $field = GenerateField::parse($param);
                $sql = 'ALTER TABLE `' . $table . '` ADD COLUMN `'
                    . $param['name'] . '` ' . $field . ' COMMENT "' . $param['title'] . '";';
                Db::execute($sql);
            } else {

                // 得出字段的类型
                $field = GenerateField::parse($param);
                $sql = 'ALTER TABLE ' . $table . ' CHANGE COLUMN `' . $param['name']
                    . '` `' . $param['name'] . '` ' . $field . ' COMMENT "' . $param['title'] . '";';
                Db::execute($sql);
            }

        } catch (\Exception $e) {

            return ['code' => -1, 'data' => [], 'msg' => $e->getMessage()];
        }

        return ['code' => 0, 'data' => [], 'msg' => '编辑成功'];
    }

    /**
     * 删除内容字段
     * @param $fieldId
     * @param $fieldName
     * @param $modelId
     * @return array
     */
    public function delField($fieldId, $fieldName, $modelId)
    {
        try {

            $this->where('id', $fieldId)->delete();

            // 找到对应的模型字段表，编辑对应的字段
            $modelxModel = new Modelx();
            $modelInfo = $modelxModel->getModelById($modelId)['data'];
            $modelTable = $modelInfo['table'];
            $table = getTablePrefix() . $modelTable . '_content';

            $sql = 'ALTER TABLE `' . $table . '` DROP COLUMN `' . $fieldName . '`';
            Db::execute($sql);
        } catch (\Exception $e) {

            return ['code' => -1, 'data' => [], 'msg' => $e->getMessage()];
        }

        return ['code' => 0, 'data' => [], 'msg' => '删除成功'];
    }
}